//
//  RemotePlaybackListCell.swift
//  ZhiTing
//
//  Created by macbook on 2022/5/11.
//
#if !(targetEnvironment(simulator))
import UIKit
import SwiftUI

class RemotePlaybackListCell: UITableViewCell, ReusableView {

    var openCallback: (() -> ())?
    var videoCallback: ((_ index: Int) -> ())?

    //是否为第一个cell
    var isFirstCell: Bool? {
        didSet {
            guard let result = isFirstCell else {return}
            if result {//为第一个cell
                line.snp.remakeConstraints {
                    $0.centerX.equalTo(dotView)
                    $0.top.equalTo(dotView.snp.bottom)
                    $0.bottom.equalToSuperview()
                    $0.width.equalTo(2)
                }
            }else{
                if isLastCell {
                    line.snp.remakeConstraints {
                        $0.centerX.equalTo(dotView)
                        $0.top.equalToSuperview()
                        $0.bottom.equalTo(dotView.snp.top)
                        $0.width.equalTo(2)
                    }
                }else{
                    line.snp.remakeConstraints {
                        $0.centerX.equalTo(dotView)
                        $0.top.bottom.equalToSuperview()
                        $0.width.equalTo(2)
                    }
                }

            }
        }
    }
    
    //是否为最后一个cell
    var isLastCell = false
    
    //是否选中当下cell
    var isOpen: Bool? {
        didSet {
            guard let result = isOpen else {return}
            if result {//已选择当前cell,展开
                dotView.backgroundColor = .custom(.blue_3699ff)
                dateLabel.textColor = .custom(.blue_3699ff)
                arrow.setImage(.assets(.arrow_up), for: .normal)
                collectionView.isHidden = false
                
                dotView.snp.remakeConstraints {
                    $0.top.equalTo(20)
                    $0.left.equalTo(15)
                    $0.width.height.equalTo(10)
                }
                let height = countCollectionViewHeight()
                collectionView.snp.remakeConstraints {
                    $0.top.equalTo(dateLabel.snp.bottom).offset(15)
                    $0.left.equalTo(dateLabel)
                    $0.right.equalTo(arrow)
                    $0.height.equalTo(height)
                    $0.bottom.equalToSuperview().offset(-10)
                }
                collectionView.reloadData()
            }else{
                dotView.backgroundColor = .custom(.gray_eeeeee)
                dateLabel.textColor = .custom(.black_3f4663)
                arrow.setImage(.assets(.arrow_down), for: .normal)
                collectionView.isHidden = true
                dotView.snp.remakeConstraints {
                    $0.top.equalTo(20)
                    $0.left.equalTo(15)
                    $0.width.height.equalTo(10).priority(.high)
                    $0.bottom.equalTo(-20)
                }
                
                collectionView.snp.remakeConstraints {
                    $0.top.equalTo(dateLabel.snp.bottom).offset(15)
                    $0.left.equalTo(dateLabel)
                    $0.right.equalTo(arrow)
                    $0.height.equalTo(10)
                }
            }
        }
    }
    

    //数据传入刷新UI
    var datas: [TFDataListModel]? {
        didSet{
            //设置model，重新刷新UI
            DispatchQueue.main.async {[weak self] in
                self?.collectionView.reloadData()
            }
        }
    }
    
    
    
    lazy var bgView = UIView().then{
        $0.backgroundColor = .custom(.white_ffffff)
    }
    
    lazy var dotView = UIView().then {
        $0.backgroundColor = .custom(.white_ffffff)
        $0.layer.cornerRadius = 5
        $0.layer.masksToBounds = true
    }
    
    lazy var line = UIView().then {
        $0.backgroundColor = .custom(.gray_eeeeee)
    }
    
    lazy var dateLabel = Label().then {
        $0.textColor = .custom(.black_3f4663)
        $0.font = .font(size: 16, type: .bold)
        $0.isUserInteractionEnabled = true
        $0.addGestureRecognizer(UITapGestureRecognizer(target: self, action: #selector(openOrCloseAction)))
    }
    
    lazy var arrow = Button().then {
        $0.isEnhanceClick = true
        $0.setImage(.assets(.arrow_down), for: .normal)
        $0.clickCallBack = {[weak self] _ in
            self?.openCallback?()
        }
    }
    
    @objc
    private func openOrCloseAction(){
        self.openCallback?()
    }
    
    //设备列表
    private lazy var flowLayout = UICollectionViewFlowLayout().then {
        $0.itemSize = CGSize(width: ZTScaleValue(100), height:  ZTScaleValue(30))
        //行列间距
        $0.minimumLineSpacing = ZTScaleValue(15)
        $0.minimumInteritemSpacing = ZTScaleValue(10)
        
    }
    lazy var collectionView = UICollectionView(frame: .zero, collectionViewLayout: flowLayout).then{
        $0.backgroundColor = .clear
        $0.backgroundColor = .clear
        $0.delegate = self
        $0.dataSource = self
        $0.isHidden = true
        $0.showsHorizontalScrollIndicator = false
        $0.showsVerticalScrollIndicator = false
        $0.alwaysBounceVertical = true
        $0.alwaysBounceHorizontal = false
        $0.isUserInteractionEnabled = true
        $0.register(RemotePlaybackTimeCell.self, forCellWithReuseIdentifier: RemotePlaybackTimeCell.reusableIdentifier)
    }

    
    override func awakeFromNib() {
        super.awakeFromNib()
        // Initialization code
    }

    override func setSelected(_ selected: Bool, animated: Bool) {
        super.setSelected(selected, animated: animated)

        // Configure the view for the selected state
    }
    
    override init(style: UITableViewCell.CellStyle, reuseIdentifier: String?) {
        super.init(style: style, reuseIdentifier: reuseIdentifier)
        setupViews()
        setupConstraints()
    }
    
    required init?(coder: NSCoder) {
        fatalError("init(coder:) has not been implemented")
    }
    
    private func setupViews(){
        contentView.backgroundColor = .custom(.white_ffffff)
        contentView.addSubview(bgView)
        bgView.addSubview(line)
        bgView.addSubview(dotView)
        bgView.addSubview(dateLabel)
        bgView.addSubview(arrow)
        bgView.addSubview(collectionView)
    }
    
    private func setupConstraints(){
        bgView.snp.makeConstraints {
            $0.edges.equalToSuperview()
        }
        
        dotView.snp.makeConstraints {
            $0.top.equalTo(20)
            $0.left.equalTo(15)
            $0.width.height.equalTo(10)
        }
        
        dateLabel.snp.makeConstraints {
            $0.centerY.equalTo(dotView)
            $0.left.equalTo(dotView.snp.right).offset(10)
            $0.right.equalTo(arrow.snp.left)
        }
        
        arrow.snp.makeConstraints {
            $0.centerY.equalTo(dotView)
            $0.right.equalTo(-15)
            $0.width.equalTo(15)
            $0.height.equalTo(8)
        }
        
        line.snp.makeConstraints {
            $0.centerX.equalTo(dotView)
            $0.top.bottom.equalToSuperview()
            $0.width.equalTo(2)
        }
        
        collectionView.snp.makeConstraints {
            $0.top.equalTo(dateLabel.snp.bottom).offset(15)
            $0.left.equalTo(dateLabel)
            $0.right.equalTo(arrow)
            $0.height.equalTo(10)
            $0.bottom.equalToSuperview().offset(-10)
        }
        
    }
    
    private func countCollectionViewHeight() -> CGFloat {
        //计算collection 高度
        var rowHeight = ZTScaleValue(30)
        let rowSpereterHeight = ZTScaleValue(15)
        var row = (datas?.count ?? 0) / 3
        if (datas?.count ?? 0) % 4 != 0 {
            row += 1
        }
        
        if row == 0 {
            row = 1
        }
        rowHeight = rowHeight*CGFloat(row) + CGFloat((row - 1))*rowSpereterHeight
        return rowHeight
    }


}

extension RemotePlaybackListCell: UICollectionViewDataSource, UICollectionViewDelegate {
    //cell 数量
    func collectionView(_ collectionView: UICollectionView, numberOfItemsInSection section: Int) -> Int {
        return  datas?.count ?? 0
    }
    //cell 具体内容
    func collectionView(_ collectionView: UICollectionView, cellForItemAt indexPath: IndexPath) -> UICollectionViewCell {
        let cell = collectionView.dequeueReusableCell(withReuseIdentifier: RemotePlaybackTimeCell.reusableIdentifier, for: indexPath) as! RemotePlaybackTimeCell
        guard let model = datas?[indexPath.row] else {return cell}
        cell.timeLabel.text = model.record_date_time
        cell.isChoose = model.isChoose
        return cell
    }
    
    func collectionView(_ collectionView: UICollectionView, didSelectItemAt indexPath: IndexPath) {
        if datas != nil {
//            for (index, model) in datas!.enumerated() {
//                if index == indexPath.item {
//                    model.isChoose = !model.isChoose
//                }else{
//                    model.isChoose = false
//                }
//            }
//            collectionView.reloadData()
            videoCallback?(indexPath.item)
        }
    }
}
#endif
